package com.xiaodai.miaosha.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaodai.miaosha.entity.Msuser;
import com.xiaodai.miaosha.entity.Msuser;
import com.xiaodai.miaosha.mapper.MsuserMapper;
import com.xiaodai.miaosha.service.IMsuserService;
import com.xiaodai.miaosha.utils.CookieUtil;
import com.xiaodai.miaosha.utils.UUIDUtil;
import com.xiaodai.miaosha.utils.ValidatorUtil;
import com.xiaodai.miaosha.vo.LoginVo;
import com.xiaodai.miaosha.vo.RespBean;
import com.xiaodai.miaosha.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaodai
 * @since 2022-04-12
 */
@Service
public class MsuserServiceImpl extends ServiceImpl<MsuserMapper, Msuser> implements IMsuserService {
    @Resource
    private MsuserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        Msuser Msuser = userMapper.selectOne(new QueryWrapper<Msuser>().eq("tel", mobile));
        if (!ValidatorUtil.isMobile(mobile)){
            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        }
        if (Msuser == null){
            return RespBean.error(RespBeanEnum.MOBILE_NOT_EXIST);
        }
        if (!password.equals(Msuser.getPassword())){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        String uuid = UUIDUtil.uuid();
//        request.getSession().setAttribute(uuid,Msuser);
        redisTemplate.opsForValue().set("Msuser:"+uuid,Msuser);
        CookieUtil.setCookie(request,response,"userTicket",uuid);

        return RespBean.success(uuid);
    }

    @Override
    public Msuser getUserByCookie(String uuid,HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(uuid)){
            return null;
        }
        Msuser Msuser = (Msuser) redisTemplate.opsForValue().get("Msuser:"+uuid);
        if (Msuser!=null){
            CookieUtil.setCookie(request,response,"userTicket",uuid);
        }
        return Msuser;
    }
}
